package br.com.nextsql.renderizar;

import br.com.nextsql.GlobalConf;
import java.awt.*;
import java.util.Properties;
import javax.swing.*;
import javax.swing.border.AbstractBorder;

public class BordaNumerada extends AbstractBorder {
    private int lineHeight = 16;
    private int characterHeight = 17;
    private Color myColor;
    private JViewport viewport;
    private Properties principal;
    public BordaNumerada() {
        principal = GlobalConf.lerPropriedades();
        this.myColor = new Color(164, 164, 164);
    }
    @Override
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        Font fonte = new Font(principal.getProperty("fonte"), Font.PLAIN, Integer.parseInt(principal.getProperty("fonte.tamanho")));
        g.setFont(fonte);
        FontMetrics fm = g.getFontMetrics(g.getFont());
        Color oldColor = g.getColor();
        g.setColor(this.myColor);
        double r = (double)height/(double)fm.getHeight();
        this.characterHeight = this.lineHeight = fm.getHeight();
        int rows = (int) (r + 0.5);
        int py;
        int px = 2;
        for (int i = 0; i < rows; i++) {
            py = fm.getHeight()*i+fm.getHeight()-2;
            g.drawString(String.valueOf(i+1), px, py);
        }
        int left = this.calculateLeft(height);
        g.drawLine(left, 0, left, height);
        g.setColor(oldColor);
        if (this.viewport == null) {
            searchViewport(c);
        }
    }
    @Override
    public Insets getBorderInsets(Component c) {
        int left = this.calculateLeft(c.getHeight())+4;
        return new Insets(1, left, 0, 1);
    }
    @Override
    public Insets getBorderInsets(Component c, Insets insets) {
        insets.top = 1;
        insets.left = this.calculateLeft(c.getHeight());
        insets.bottom = 1;
        insets.right = 1;
        return insets;
    }
    protected int calculateLeft(int height){
        double r = (double) height / (double) this.lineHeight;
        int rows = (int) (r + 0.5);
        String str = String.valueOf(rows);
        int lenght = str.length();
        return this.characterHeight * lenght;
    }
    protected void searchViewport(Component c) {
        Container parent = c.getParent();
        if (parent instanceof JViewport){
            this.viewport = (JViewport)parent;
        }
    }
}
